package cn.didi.feidi.androidorder.manager;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import org.afinal.simplecache.SimplceCache;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.ZipException;

import cn.didi.feidi.androidorder.OrderApplication;
import cn.didi.feidi.androidorder.model.AppInfo;
import cn.didi.feidi.androidorder.util.ZipUtil;

/**
 * 1、是否首次进入App<br />
 * 2、更新App<br />
 * <p>
 * Created by king on 2017/7/17.
 */
public class AppManager {

    private static final String TAG = "AppManager.TAG";
    private static SimplceCache mAppCache = SimplceCache.get(OrderApplication.getContext(), "app_cfg");
    private static AppInfo mAppInfo;

    /**
     * 资源文件目录
     */
    private static final String RESOURCE_FILE_DIR = OrderApplication.getContext().getFilesDir().getPath() + "/resource_file/";
    /**
     * 资源ZIP文件完全路径
     */
    private static final String RESOURCE_FILE_ZIP_DIR = OrderApplication.getContext().getFilesDir().getPath() + "/resource_file/download/";
    private static final int RESOURCE_ID = 1; // 资源ID


    public static URL getAppInfoUrl(Context context) {
        return null;
    }

    // 向服务器请求当前服务器更新的App版本信息的url
    private static URL genServiceAppInfo(int deviceType, int clientType,
                                         String clientVersion, int resVersion) {
        return null;
    }

    public static AppInfo getAppInfo() {
        if (mAppInfo == null)
            mAppInfo = (AppInfo) mAppCache.getAsObject("info_");
        return mAppInfo;
    }

    public static void putAppInfo(AppInfo appInfo) {
        mAppInfo = appInfo;
        mAppCache.put("info_", appInfo, 3 * SimplceCache.TIME_DAY);
    }

    public static boolean getFirstInAppFlag() {
        String firstFlag = mAppCache.getAsString("first_in_app_flag");
        if (firstFlag == null || "".equals(firstFlag))
            return true;
        return Boolean.valueOf(firstFlag);
    }

    public static void putFirstInAppFlag(boolean flag) {
        mAppCache.put("first_in_app_flag", String.valueOf(flag));
    }


    /**
     * App本地资源文件ID
     */
    public static void putAppResourceId(int appResID) {
        mAppCache.put("app_res_id", appResID);
    }

    /**
     * App本地资源版本ID
     */
    public static int getAppResourceId() {
        try {
            Object res_id = mAppCache.getAsObject("app_res_id");
            return Integer.valueOf(String.valueOf(res_id));
        } catch (Exception e) {
            putAppResourceId(RESOURCE_ID);
        }
        return RESOURCE_ID;
    }

    /**
     * 拷贝资源包到存储卡
     */
    public static void copyRaw2SDCard() {
    }

    private static void readCfg() throws IOException {

        Log.d(TAG, "资源配置成功！");
    }

    // 登录之前添加监听器
    public void addOnDownloadZIPListener(OnDownloadZIPListener listener) {
        mFinishListener = listener;
    }

    /**
     * @param context
     * @param downloadResURL
     * @param clientResId
     * @param serverResId
     */
    public void downloadZIP(Context context, String downloadResURL, int clientResId, int serverResId) {
        if (clientResId < serverResId) {// 如果本地资源ID小于服务器资源ID,则进行下载
            StringBuilder sbUrl;
            if (downloadResURL != null && !"".equals(downloadResURL)) {
                sbUrl = new StringBuilder(downloadResURL);
                sbUrl.append("res");
                sbUrl.append(clientResId + 1);// 本地资源ID向前加1,进行下载
                sbUrl.append(".zip");
                // 参数：下载URL,下载后的文件名
                new DownloadTask().execute(sbUrl.toString(), "res" + (clientResId + 1) + ".zip");
                ;
            }
        } else {
            try {
                readCfg();
                if (mFinishListener != null)
                    mFinishListener.onFinish();
            } catch (IOException e) {
                e.printStackTrace();
                if (mFinishListener != null)
                    mFinishListener.onError();
            }
        }
    }

    public class DownloadTask extends AsyncTask<String, String, File> {

        public DownloadTask() {
            super();
        }

        @Override
        protected File doInBackground(String... params) {
            if (params[0] == null) return null;

            try {
                String netResUrl = params[0];
                Log.i(TAG, "下载资源包：" + netResUrl);
                File mFile = new File(RESOURCE_FILE_ZIP_DIR + params[1]);
                URL url = new URL(netResUrl);
                URLConnection connection = null;
                int bytesCopied = 0;
                connection = url.openConnection();
                int length = connection.getContentLength();
                if (mFile.exists() && length == mFile.length()) {
                    Log.i(TAG, "file " + mFile.getName() + " already exits!!");
                    return mFile;
                }
                FileOutputStream mOutputStream = new FileOutputStream(mFile);
                bytesCopied = copy(connection.getInputStream(), mOutputStream);
                if (bytesCopied != length && length != -1) {
                    Log.i(TAG, "Download incomplete bytesCopied=" + bytesCopied + ", length" + length);
                }
                mOutputStream.close();
                return mFile;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(File file) {
            if (file == null) return;
            try {
                Log.i(TAG, "下载资源包成功 =" + file.getAbsolutePath());
                ZipUtil.upZipFile(file, RESOURCE_FILE_DIR);
                int curResID = getAppResourceId() + 1;
                putAppResourceId(curResID);
                AppInfo appInfo = getAppInfo();
                downloadZIP(OrderApplication.getContext(), appInfo.getResURL(), curResID, appInfo.getResVersion());
            } catch (ZipException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        private int copy(InputStream input, OutputStream output) {
            byte[] buffer = new byte[1024 * 8];
            BufferedInputStream in = new BufferedInputStream(input, 1024 * 8);
            BufferedOutputStream out = new BufferedOutputStream(output, 1024 * 8);
            int count = 0, n = 0;
            try {
                while ((n = in.read(buffer, 0, 1024 * 8)) != -1) {
                    out.write(buffer, 0, n);
                    count += n;
                }
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return count;
        }
    }

    // ngai add
    public interface OnDownloadZIPListener {
        void onFinish();

        void onError();
    }

    private OnDownloadZIPListener mFinishListener;

    public void setFinishListener(OnDownloadZIPListener mFinishListener) {
        this.mFinishListener = mFinishListener;
    }
}
